<template>
    <div class="myhead">
        <h2>My ToDo List</h2>
        <div class="box">
            <input type="text" placeholder="请输入待办事项..." class="thing" v-model="newTodo">
            <button class="add" @click="addTodo" @keyup.enter="addTodo">添加</button>
        </div>
    </div>
    <ul>
      <li v-for="(todo, index) in todos" :key="index"  @click="selectTodo(todo)" :class="{ checked: todo.checked }">
        <span v-if="!todo.editing" @dblclick.stop="editTodo(index)" class="text">{{ todo.text }}</span>
        <input v-else type="text" v-model="todo.text" @blur.stop="saveTodo(index)" @keyup.enter="saveTodo(index)" />
        <span class="close" @click="removeTodo(index)">x</span>
      </li>
    </ul>
</template>

<script setup>
import { ref,nextTick } from 'vue';

const newTodo = ref('')
const todos = ref([])
const isDoubleClicking = ref(false);

// 添加待办事项
const addTodo = () => {
  if (newTodo.value.trim() !== '') {
    todos.value.push({ text: newTodo.value, editing: false,checked:false })
    newTodo.value = ''
  }
}

// 转换编辑状态
const editTodo = (index) => {
  todos.value[index].editing = true
  // 聚焦输入框,使用nextTick防止闪烁
  nextTick(() => {
    const input = document.querySelector(`li:nth-child(${index + 1}) input`)
    if (input) {
      input.focus()
    }
  })
}

// 保存编辑后的待办事项
const saveTodo = (index) => {
  todos.value[index].editing = false
}

// 删除待办事项
const removeTodo = (index) => {
  todos.value.splice(index, 1)
  newTodo.value = ''
}
// 选中待办事项
const selectTodo = (item) => {
  item.checked = !item.checked
}


</script>